<?php (defined('BASEPATH')) OR exit('No direct script access allowed');

class Payroll_Model extends CI_Model {
	
	private $table= 'payroll_period';
	private $shiftingModel;
	private $clientModel;
	function __construct() {
		parent::__construct();
		$this->shiftingModel = $this->load->model('Shifting_Model');
		$this->clientModel = $this->load->model('Client_Model');
		$this->userModel = $this->load->model('User_Model');
		$this->load->helper('DateUtils');
		$this->load->helper('ConstantsUtils');
	}
	
	function timeInOut ($userId, $timeIn, $timeOut){
		$shiftId = $this->shiftingModel->getShiftId($userId);
		$data = array('time_in'=>$timeIn, 'time_out'=>$timeOut, 'user_id'=>$userId, 'shift_id'=>$shiftId);
		$this->db->insert($this->table, $data);
		return $this->db->insert_id();
	}

	public function getObject($table, $filter=array()){
		$query = $this->db->get_where('payroll_period',$filter,1,0);
		$result = $query->result();
		if(!empty($result)){
			return (!empty($filter))?$result[0]:$result;
		} else {
			return false;
		}
	}
	
	public function getAllPayrollByClient($api){
		
	}
	
	public function getPayrollPeriod($api, $payroll_period_id){
		$client = $this->clientModel->find($api);
		$this->db->select("p.*");
		$this->db->from('client_payroll_period as cp');
		$this->db->join('payroll_period as p','p.id = cp.payroll_period_id','left');
		$this->db->where('cp.client_id', $client->id); 
		$this->db->where('p.id', $payroll_period_id); 
		$query = $this->db->get();
		$result = $query->result();
		if(!empty($result)){
			return $result[0];
		} else {
			return false;
		}
	}
	
	public function getAllPayrollPeriods($api, $payroll_period_id){
		//list($a,$code) = explode("-",$api);
		$client = $this->clientModel->find($api);
		//echo $client->id;
		$this->db->select("p.*");
		$this->db->from('payroll_period as p');
		$this->db->join('client_payroll_period as cp','cp.payroll_period_id = p.id','left');
		//$this->db->join('clients as c','c.id=cp.client_id','left');
		$this->db->where('cp.client_id', $client->id); 
		//$this->db->where('c.code', $code); 
		if(is_numeric($payroll_period_id) && $payroll_period_id > 0) {
			$this->db->where('p.id', $payroll_period_id);
		}
		$query = $this->db->get();
			
		return $query->result();
	}
	
	function getClientPayrollPeriods($api){
		$client = $this->clientModel->find($api);
		$this->db->select("pp.*");
		$this->db->from('payroll_period as pp');
		$this->db->join('client_payroll_period as cp','cp.payroll_period_id = pp.id','left');
		$this->db->where('client_id', $client->id);
		$query = $this->db->get();
		return $query->result();
	}
	
	function computeDay($timesheet){
		$user_payroll = array();
		// ABSENT
		if($timesheet->remarks == '1') {
			return false;
		}
		$normal_hours = 8;
		$this->load->model('Holiday_Model');
		$this->load->model('User_Model');
		
		$holiday = $this->Holiday_Model->getDay($ts->date);
		$user_id = $timesheet->user_id;
		$isRestDay = $this->User_Model->isUserRestDay($user_id, $day);	
		$user_rate = $this->User_Model->getUserRate($user_id);
		
		$regular_rate = $normal_hours * $user_rate[0]->hourly;
		$worked_hours = DateUtils::time_to_decimal($timesheet->total_hours)/60;
		$approved_ot = DateUtils::time_to_decimal($timesheet->approved_overtime)/60;
		$approved_diff = DateUtils::time_to_decimal($timesheet->approved_night_differential)/60;
		if(!empty($holiday)) {
			$regular_rate *= ($holiday[0]->percent)/ 100;
			$user_payroll['holiday']['hours'] = $normal_hours;
			$user_payroll['holiday']['type'] = $holiday[0]->type_name;
			$user_payroll['holiday']['rate'] = $regular_rate;
		}
		
		if(!empty($isRestDay)){
			$regular_rate *= (1 + ($holiday[0]->excess_percent/100));
			$user_payroll['rest_day']['hours'] = $normal_hours;
			$user_payroll['rest_day']['rate'] = $regular_rate;
		}
		
		if($approved_ot > 0) {
			$ot_rate = ($approved_ot * $user_rate[0]->hourly ) * (1 + ($holiday[0]->excess_percent/100) );
		}
		
		if($approved_diff > 0){
			
		}
		
		//if()
		

	}
	
	function userPayroll($api, $payroll_period_id, $user_id){
		$client = $this->clientModel->find($api);
		$this->db->select('p.*');
		$this->db->from('payroll as p');
		$this->db->join('users as u','u.id = p.user_id','left');
		$this->db->join('clients as c','c.id = u.client_id','left');
		$this->db->where('c.id', $client->id);
		$this->db->where('p.user_id', $user_id);
		$this->db->where('p.payroll_period_id', $payroll_period_id);
		$query = $this->db->get();
		return $query->result();
	}
	
	function save($data,$payroll_period_id,$user_id){
		//var_dump($data);
		$params = array(
			'user_id' => $user_id,
			'payroll_period_id' =>$payroll_period_id,
			'regular_hours' => $data['data']->total_days * ConstantsUtils::$EMPLOYEE_REGULAR_HOURS,
			'regular_overtime' => DateUtils::time_to_decimal($data['data']->total_approved_overtime)/60,
			'approved_undertime' => DateUtils::time_to_decimal($data['data']->total_approved_undertime)/60,
			'approved_late' => DateUtils::time_to_decimal($data['data']->total_approved_late)/60,
			'regular_night_differential' => DateUtils::time_to_decimal($data['data']->total_night_differential)/60,
			'restday' =>$data['rest_day']->rest_day * ConstantsUtils::$EMPLOYEE_REGULAR_HOURS,
			'excess_restday' => DateUtils::time_to_decimal($data['rest_day']->excess)/60,
			'restday_night_differential' => DateUtils::time_to_decimal($data['rest_day']->night_differential)/60,
			'special_holiday' => isset($data['special_holiday']['days'])?$data['special_holiday']['days']:0,
			'excess_special_holiday' => isset($data['special_holiday']['excess'])?$data['special_holiday']['excess']:0,
			'special_holiday_night_differential' =>isset($data['special_holiday']['night_differential'])?$data['special_holiday']['night_differential']:0,
			'special_holiday_restday' => 0,
			'excess_special_holiday_restday' => 0,
			'legal_holiday' => $data['regular_holiday']['days'] * ConstantsUtils::$EMPLOYEE_REGULAR_HOURS,
			'excess_legal_holiday' => isset($data['regular_holiday']['excess'])?$data['regular_holiday']['excess']:0,
			'legal_holiday_night_differential'=>isset($data['regular_holiday']['night_differential'])?$data['regular_holiday']['night_differential']:0
		);
		$this->db->insert('payroll',$params);
		return $this->db->insert_id();
		
	}
	
	function updateField($api, $params, $payroll_period_id, $user_id, $pid){
		$this->db->where('id',$pid);
		$this->db->where('payroll_period_id',$payroll_period_id);
		$this->db->where('user_id',$user_id);
		$this->db->update('payroll',$params);
	}
	
	
	function getAllByPeriod($api, $payroll_period_id){
		$client = $this->clientModel->find($api);
		if(isset($client)) {
			$this->db->select('p.*, pr.first_name,pr.middle_name,pr.last_name');
			$this->db->from('payroll as p');
			$this->db->join('users as u','u.id = p.user_id','left');
			$this->db->join('clients as c','c.id = u.client_id','left');
			$this->db->join('file201 as pr','pr.user_id = u.id','left');
			$this->db->where('c.id', $client->id);
			$this->db->where('p.payroll_period_id', $payroll_period_id);
			$query = $this->db->get();
			return $query->result();	
		}
		
	
	}
	
	function compute($data){
		$rate = $this->userModel->getUserRate($data->user_id);
		$regular_hours = $data->regular_hours * $rate[0]->regular_hours;
		$regular_overtime = $data->regular_overtime * $rate[0]->regular_overtime;
		$regular_night_differential = $data->regular_night_differential * $rate[0]->regular_night_diff;
		$restday = $data->restday * $rate[0]->rest_day;
		$excess_restday = $data->excess_restday * $rate[0]->excess_rest_day;
		$restday_night_differential = $data->restday_night_differential * $rate[0]->rest_day_night_diff;
		$special_holiday = $data->special_holiday * $rate[0]->special_holiday;
		$excess_special_holiday = $data->excess_special_holiday * $rate[0]->excess_on_special_holiday;
		$special_holiday_night_differential = $data->special_holiday_night_differential * $rate[0]->special_holiday_night_diff;
		$special_holiday_restday = $data->special_holiday_restday * $rate[0]->special_holiday_on_rest_day;
		$excess_special_holiday_restday = $data->excess_special_holiday_restday * $rate[0]->excess_special_holiday_on_rest_day;
		$legal_holiday = $data->legal_holiday * $rate[0]->legal_holiday;
		$excess_legal_holiday = $data->excess_legal_holiday * $rate[0]->excess_legal_holiday;
		$legal_holiday_restday = $data->legal_holiday_restday * $rate[0]->legal_holiday_rest_day;
		$excess_legal_holiday_restday = $data->excess_legal_holiday_restday * $rate[0]->excess_legal_holiday_rest_day;
		$legal_holiday_night_differential = $data->legal_holiday_night_differential * $rate[0]->legal_holiday_night_diff;
		//deductions
		$tax = $data->tax;
		$sss = $data->sss;
		$philhealth = $data->philhealth;
		$hdmf = $data->hdmf;
		$sss_loan = $data->sss_loan;
		$hdmf_loan = $data->hdmf_loan;
		$other_deductions = $data->other_deductions;
		$approved_late = $data->approved_late * $rate[0]->regular_hours;
		$approved_undertime = $data->approved_undertime * $rate[0]->regular_hours;
		
		$total_deductions = $tax + $sss + $philhealth + $hdmf + $hdmf_loan + $sss_loan + $other_deductions + $approved_late + $approved_undertime;
		
		$total = $regular_hours + $regular_overtime + $regular_night_differential + $restday + $excess_restday + $restday_night_differential;
		$total += $special_holiday + $excess_special_holiday + $special_holiday_night_differential + $special_holiday_restday;
		$total += $excess_special_holiday_restday + $legal_holiday + $excess_legal_holiday + $legal_holiday_restday;
		$total += $excess_legal_holiday_restday + $legal_holiday_night_differential;
		return $total - $total_deductions;
	}
	
	function getCountPayrollStatus($api,$payroll_period_id, $status){
		$client = $this->clientModel->find($api);
		$this->db->select('p.*');
		$this->db->from('payroll as p');
		$this->db->join('users as u','u.id = p.user_id','left');
		$this->db->join('clients as c','c.id = u.client_id','left');
		$this->db->where('c.id',$client->id);
		$this->db->where('p.payroll_period_id', $payroll_period_id);
		$this->db->where('p.status', $status);
		$query = $this->db->get();
		return $query->num_rows();
	}
	
	function saveOrUpdatePayrollAmount($api, $params, $pid = 0){
		if($pid > 0) {
			$this->db->where('pid',$pid);
			$this->db->update('final_payroll', $params);
			return true;
		} else {
			$this->db->insert('final_payroll', $params);
			return $this->db->insert_id();
		}
	}
	
	function saveOrUpdatePayroll($api, $params, $id = 0){
		$client = $this->clientModel->find($api);
		$isAllowed = $this->userModel->isClientAllowed($client->id, $params['user_id']);
		if($isAllowed){
			if($id > 0) {
				$this->db->where('id',$id);
				$this->db->update('payroll',$params);
				return true;
			} else {
				$this->db->insert('payroll', $params);
				return $this->db->insert_id();
			}
		}
		
	}
	
}